package formal.tree.ergodic;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author DengYuan2
 * @create 2021-01-19 21:04
 */
public class E_637 {
    public static void main(String[] args) {
        Integer[] a ={3,9,20,null,null,15,7};
        TreeNode treeNode = TreeNode.generateTree(a);
        List<Double> list = averageOfLevels(treeNode);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

    }

    public static List<Double> averageOfLevels(TreeNode root) {
        if (root==null){
            return new ArrayList<Double>();
        }
        ArrayList<Double> res = new ArrayList<>(16);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int size = 0;
        double avg = 0.0;
        double sum =0;
        while (!queue.isEmpty()){
            size=queue.size();
            sum=0;
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                sum+=poll.val;
                if (poll.left!=null){
                    queue.offer(poll.left);
                }
                if (poll.right!=null){
                    queue.offer(poll.right);
                }
            }
            avg=sum/size;
            res.add(avg);
        }
        return res;
    }
}
